package com.primus.server.security.authentication;

import com.primus.server.entity.user.User;
import com.primus.server.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;

@Component
public class SelfUserDetailsService implements UserDetailsService {

    private final UserService userService;

    @Autowired
    public SelfUserDetailsService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)) {
            throw new UsernameNotFoundException("username was not exist");
        }
        SelfUserDetails userInfo = new SelfUserDetails();
        User user = userService.findByAccount(username);
        if (user == null) {
            throw new UsernameNotFoundException("user " + username + " was not found in db");
        }
        userInfo.setUsername(user.getAccount());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        userInfo.setPassword(passwordEncoder.encode(user.getPassword()));
        Collection<GrantedAuthority> grantedAuthorities = user.getRoles().stream().map(r ->
                new SimpleGrantedAuthority(r.getName())).collect(Collectors.toList());
        userInfo.setAuthorities(grantedAuthorities);
        return userInfo;
    }
}
